package utils

import (
	"cake-server/module"
	"strings"

	"github.com/gin-gonic/gin"
)

type FormatMenus struct {
	module.Menu
	Children []FormatMenus `json:"children"`
}

// ResolveMenus 解析菜单
func ResolveMenus(menus []module.Menu) []FormatMenus {
	var formatMenus []FormatMenus
	for _, menu := range menus {
		// 如果是一级菜单
		if menu.ParentId == nil {
			formatMenus = append(formatMenus, FormatMenus{
				Menu:     menu,
				Children: getChildren(menu.Id, menus),
			})
		}
	}
	return formatMenus
}

// getChildren 获取子菜单
// 递归获取子菜单
func getChildren(parentId int, menus []module.Menu) []FormatMenus {
	var children []FormatMenus
	for _, menu := range menus {
		if menu.ParentId != nil && *menu.ParentId == parentId {
			children = append(children, FormatMenus{
				Menu:     menu,
				Children: getChildren(menu.Id, menus),
			})
		}
	}
	return children
}

// 处理静态文件中间件
func ResolveStatic(c *gin.Context) {
	if strings.HasPrefix(c.Request.URL.Path, "/static/") {
		c.Header("Cache-Control", "public, max-age=31536000")
	}
}

func VagueFormat(str string) string {
	return "%" + str + "%"
}
